import sys

import xbmc
import xbmcgui
import xbmcaddon
import adlm_scrapper
import threading

Addon = sys.modules['__main__'].Addon
getLS = Addon.getLocalizedString

class GUI(xbmcgui.WindowXML):
    
    #Actions
    """ https://github.com/xbmc/xbmc/blob/master/xbmc/guilib/Key.h """
    ACTION_MOVE_LEFT = [1]
    ACTION_MOVE_RIGHT = [2]
    ACTION_MOVE_UP = [3]
    ACTION_MOVE_DOWN = [4]
    ACTION_SELECT_ITEM = [7]
    ACTION_HIGHLIGHT_ITEM = [8]
    ACTION_PARENT_DIR = [9]
    ACTION_PREVIOUS_MENU = [10]
    ACTION_SHOW_INFO = [11]
    ACTION_PAUSE = [12]
    ACTION_STOP = [13]
    ACTION_PLAY = [68]
    ACTION_CONTEXT_MENU = [117]
    ACTION_BUILT_IN_FUNCTION = [122]
    
    COMMAND_OPTIONS = [117, 122]
    COMMAND_NAV = [1, 2, 3, 4, 10, 13]
    COMMAND_BACK = [9, 10, 13]
    COMMAND_SHOW_INFO = [11]
    COMMAND_PAUSE = [12]
    COMMAND_RESUME = [12, 68]
    COMMAND_LIST_UP_DOWN = [3, 4]
    
    #CONTROL
    GROUP_BROWSING = 1000
    CONTROL_LOADING = 20001
    CONTROL_LIST = 10100
    CONTROL_ICON = 10200
    CONTROL_TITLE = 10300
    
    GROUP_VIEWER = 2000
    CONTROL_LIST_IMG = 20000
    CONTROL_LIST_LABEL_COUNT = 20001 #used to disable the focus.
    CONTROL_PAUSE_IMG = 20100
    
    GROUP_CARD = 3000
    CONTROL_CARD_TITLES = 30101
    CONTROL_CARD_TEXT = 30102
    CONTROL_CARD_INTERESTS = 30103
    CONTROL_CARD_THUMB = 30104
    
    #CONTEXT
    CTX_MENU = 'menu'
    CTX_PROVIDERS = 'providers'
    CTX_SEARCH = 'search'
    CTX_SLIDESHOW = 'slideshow'
    CTX_SERIES = 'series'
    CTX_IMAGES = 'images'
    
    timerValues = { '0':5.0, '1':7.0, '2':10.0, '3':15.0, '4':30.0, '5':60.0 }
    
    
    def onInit(self):
        self.adlm = adlm_scrapper.Adlm()
        self.context = self.CTX_MENU
               
        self.showInfo = 'true'
        self.showCard = False
        
        self.getControl(self.GROUP_CARD).setVisible(self.showCard)
        self.getControl(self.GROUP_VIEWER).setVisible(False) # fixme: seems like that if false in xml, won't be possible to show
        self.getControl(self.CONTROL_LOADING).setLabel(getLS(32001))  # fixme: bug right now in xbmc -> not working with id in xml file
        self.getControl(self.CONTROL_CARD_TITLES).setLabel(getLS(34001) + '\n' + getLS(34002) + '\n' + getLS(34003) + '\n' + getLS(34004) + '\n' + getLS(34005) + '\n' + getLS(34006))
        
        self.slideShowIndex = -1
        self.slideShowMode = Addon.getSetting('mode');
        self.slideShowCategories = Addon.getSetting('categories');
        
        self.username = Addon.getSetting('categories');
        self.password = Addon.getSetting('password');
        self.timerDelay = self.timerValues.get(Addon.getSetting('display_time'), 10.0)
        
        self.currentItemIndex = 0
        
        self.myTimer = threading.Timer(self.timerDelay, self.timerUpdate)
        
        self.setPauseVisible(False)
        self.showMenu()
        
    def setPauseVisible(self, isVisible):
        self.slideShowIsPaused = isVisible
        self.getControl(self.CONTROL_PAUSE_IMG).setVisible(self.slideShowIsPaused)
    
    def timerUpdate(self):
        # update the image we see
        lstCtrl = self.getControl(self.CONTROL_LIST_IMG)
        self.imageIndex = (self.imageIndex + 1) % lstCtrl.size()
        self.setIdolInfo(lstCtrl.getListItem(self.imageIndex))
        lstCtrl.selectItem(self.imageIndex)
        
        self.resumeTimer() # start the timer now so we don't wait during the http request.
        
        # update the self.images and the control as well
        startIndex = 0
        endIndex = -1
        if self.imageIndex == lstCtrl.size() / 2:
            self.slideShowIndex = self.slideShowIndex + lstCtrl.size()
            self.images = self.adlm.getRandomPictures(self.slideShowIndex)
            endIndex = (lstCtrl.size() / 2) - 1
        elif (self.imageIndex == 0):
            startIndex = (lstCtrl.size() / 2) - 1
            endIndex = lstCtrl.size()
        
        if endIndex > len(self.images):
            endIndex = len(self.images)
        
        if endIndex != -1:
            i = startIndex
            for i in range(startIndex, endIndex):
                item = self.images[i]
                item['pic'] = self.adlm.getPictureUrl(item['id'])
                item['title'] = item['model']
                if len(item['serie']) > 1:
                    item['title'] = item['title'] + ' - ' + item['serie']
                item['src'] = item['provider'] + ' - ' + item['category']
                self.setListItem(self.CONTROL_LIST_IMG, item, i)
                i = i + 1
                if (i == endIndex):
                    break;
        
    def getProperty(self, property, controlId=CONTROL_LIST):
        return self.getControl(controlId).getSelectedItem().getProperty(property)
        
    def onClick(self, controlId):
        if self.context == self.CTX_PROVIDERS:
            self.onProviderClick(controlId)
        elif self.context == self.CTX_IMAGES:
            self.onImageClick(controlId)
        elif self.context == self.CTX_MENU:
            self.onMenuClick(controlId)
        elif self.context == self.CTX_SERIES:
            self.onSeriesClick(controlId)
        elif self.context == self.CTX_SLIDESHOW:
            self.onImageClick(controlId)
    
    def onMenuClick(self, controlId):
        if controlId == self.CONTROL_LIST:
            ctx = self.getProperty('context')
            if ctx == self.CTX_PROVIDERS:
                self.showCategories()
            elif ctx == self.CTX_SLIDESHOW:
                self.showSlideShow()
    
    def onProviderClick(self, controlId):
        if controlId == self.CONTROL_LIST:
            ctx = self.getProperty('context')
            if ctx == self.CTX_MENU:
                self.showMenu()
            else:
                self.category = self.getProperty('category')
                self.provider = self.getProperty('provider')
                self.showSeries()
                
    def onSeriesClick(self, controlId):
        if controlId == self.CONTROL_LIST:
            ctx = self.getProperty('context')
            if ctx == self.CTX_PROVIDERS:
                self.showCategories()
            else:
                self.setIdolInfo(self.getControl(self.CONTROL_LIST).getSelectedItem())
                self.serieId = self.getProperty('serieId')
                self.model = self.getProperty('model')
                self.serie = self.getProperty('serie')
                self.showSerie()
        	
    def onImageClick(self, controlId):
        if controlId == self.CONTROL_LIST_IMG:
            self.toggleImageInfo()

    def message(self, message):
        dialog = xbmcgui.Dialog()
        dialog.ok(" My message title", message)

    def onFocus(self, controlId):
        if controlId == self.CONTROL_LIST:
            self.updateIcon()
    
    def updateIcon(self):
        #self.message('Control id: %s with %s' % (controlId, self.getControl(self.CONTROL_LIST).getSelectedPosition()))
        try:
            self.getControl(self.CONTROL_ICON).setImage(self.getProperty('icon'))
        except:
            self.getControl(self.CONTROL_ICON).setImage('')

    def onAction(self, action):
        if action in self.COMMAND_NAV:
            self.updateIcon()
        if self.context == self.CTX_MENU:
            self.onMenuAction(action)
        elif self.context == self.CTX_PROVIDERS:
            self.onProviderAction(action)
        elif self.context == self.CTX_SERIES:
            self.onSeriesAction(action)
        elif self.context == self.CTX_IMAGES:
            self.onImagesAction(action)
        elif self.context == self.CTX_SLIDESHOW:
            self.onSlideshowAction(action)

    def onImagesAction(self, action):
        if action in self.COMMAND_BACK:
            self.cancelTimer()
            self.getControl(self.GROUP_BROWSING).setVisible(True)
            self.getControl(self.GROUP_VIEWER).setVisible(False)
            self.showSeries()
        elif action in self.COMMAND_SHOW_INFO:
            self.toggleImageInfo()
        else:
            self.setFocus(self.getControl(self.CONTROL_LIST_IMG))
                
    def onSlideshowAction(self, action):
        if action in self.COMMAND_BACK:
            self.cancelTimer()
            self.getControl(self.GROUP_BROWSING).setVisible(True)
            self.getControl(self.GROUP_VIEWER).setVisible(False)
            self.setPauseVisible(False)
            self.showMenu()
        elif action in self.COMMAND_PAUSE and not self.slideShowIsPaused:
            self.setPauseVisible(True)
            self.cancelTimer()
        elif action in self.COMMAND_RESUME and self.slideShowIsPaused:
            self.setPauseVisible(False)
            self.resumeTimer()
        elif action in self.COMMAND_SHOW_INFO:
            self.toggleImageInfo()
        else:
            self.setFocus(self.getControl(self.CONTROL_LIST_LABEL_COUNT))
            
    def onMenuAction(self, action):
        if action in self.COMMAND_BACK:
            self.cancelTimer()
            self.close()
        elif action in self.COMMAND_LIST_UP_DOWN:
            self.setupListBrowsing()
        else:
            #self.message('id:' + str(action.getId()) + ', button:' + str(action.getButtonCode()))
            self.setFocus(self.getControl(self.CONTROL_LIST))

    def onSeriesAction(self, action):
        if action in self.COMMAND_BACK:
            self.showCategories()
        elif action in self.COMMAND_LIST_UP_DOWN:
            self.setupListBrowsing()
        else:
            self.setFocus(self.getControl(self.CONTROL_LIST))
            
    def onProviderAction(self, action):
        if action in self.COMMAND_BACK:
            self.showMenu()
        elif action in self.COMMAND_LIST_UP_DOWN:
            self.setupListBrowsing()
        else:
            self.setFocus(self.getControl(self.CONTROL_LIST))
            
    def showMenu(self):
        self.context = self.CTX_MENU
        self.getControl(self.CONTROL_TITLE).setLabel(getLS(32002))
        lstCtrl = self.getControl(self.CONTROL_LIST)
        lstCtrl.reset()
        item = {'text':getLS(33001), 'context':self.CTX_PROVIDERS, 'icon':'categories.png'}
        self.addListItem(self.CONTROL_LIST, item)
        item = {'text':getLS(33002), 'context':self.CTX_SLIDESHOW, 'icon':'slideshow.png'}
        self.addListItem(self.CONTROL_LIST, item)
        #item = {'text':getLS(33003), 'context':self.CTX_SEARCH, 'icon':'search.png'}
        #self.addListItem(self.CONTROL_LIST, item)
        self.setFocus(lstCtrl)
        self.getControl(self.CONTROL_ICON).setImage('categories.png')
        self.currentItemIndex = 0
    
    def showCategories(self):
        self.context = self.CTX_PROVIDERS
        self.getControl(self.CONTROL_TITLE).setLabel(getLS(33001))
        categories = self.adlm.getCategories()
        lstCtrl = self.getControl(self.CONTROL_LIST)
        lstCtrl.reset()
        item = {'text':getLS(33101), 'context':self.CTX_MENU, 'icon':'back.png'}
        self.addListItem(self.CONTROL_LIST, item)
        for item in categories:
            item['text'] = item['provider'] + ' - ' + item['category']
            item['context'] = self.CTX_SERIES
            item['icon'] = item['provider'] + ".png"
            self.addListItem(self.CONTROL_LIST, item)
        self.setFocus(lstCtrl)
        self.getControl(self.CONTROL_ICON).setImage('back.png')
        self.currentItemIndex = 0
        
    def setupListBrowsing(self):
        lstCtrl = self.getControl(self.CONTROL_LIST)
        firstItemIndex = 0
        lastItemIndex = lstCtrl.size() - 1
        self.previousItemIndex = self.currentItemIndex
        self.currentItemIndex = lstCtrl.getSelectedPosition()
        if lastItemIndex > 0 and self.previousItemIndex == self.currentItemIndex:
            if self.currentItemIndex == firstItemIndex:
                lstCtrl.selectItem(lastItemIndex)
                self.currentItemIndex = lastItemIndex
            elif self.currentItemIndex == lastItemIndex:
                lstCtrl.selectItem(firstItemIndex)
                self.currentItemIndex = firstItemIndex
        
    def showSeries(self):
        self.context = self.CTX_SERIES
        self.getControl(self.CONTROL_TITLE).setLabel(self.provider + ' - ' + self.category)
        series = self.adlm.getSeries(self.provider, self.category)
        lstCtrl = self.getControl(self.CONTROL_LIST)
        lstCtrl.reset()
        item = {'text':getLS(33101), 'context':self.CTX_PROVIDERS, 'icon':'back.png'}
        self.addListItem(self.CONTROL_LIST, item)
        for item in series:
            #id, model, serie, providerNumber, providerName, category
            item['text'] = item['model']
            item['context'] = self.CTX_IMAGES
            item['icon'] = 'thumb_girl.png' # todo: create thumbs on the site? or cache an image somewhere?
            self.addListItem(self.CONTROL_LIST, item)
        self.setFocus(lstCtrl)
        self.getControl(self.CONTROL_ICON).setImage('back.png')
        self.currentItemIndex = 0
        
    def showSearchResult(self, terms):
        self.context = self.CTX_SEARCH
        self.getControl(self.CONTROL_TITLE).setLabel(getLS(33003) + ': ' + terms)
        searchResults = self.adlm.searchSeries(terms)
        lstCtrl = self.getControl(self.CONTROL_LIST)
        lstCtrl.reset()
        item = {'text':getLS(33101), 'context':self.CTX_MENU, 'icon':'back.png'}
        self.addListItem(self.CONTROL_LIST, item)
        for item in series:
            item['text'] = item['model'] + '(' + item['provider'] + ' - ' + item['category'] + ')'
            item['context'] = self.CTX_IMAGES
            item['icon'] = 'thumb_girl.png' # todo: create thumbs on the site? or cache an image somewhere?
            self.addListItem(self.CONTROL_LIST, item)
        self.setFocus(lstCtrl)
        self.getControl(self.CONTROL_ICON).setImage('back.png')
        self.currentItemIndex = 0

    def showSerie(self):
        self.context = self.CTX_IMAGES
        self.images = self.adlm.getPictures(self.serieId)
        
        lstCtrl = self.getControl(self.CONTROL_LIST_IMG)
        lstCtrl.reset()
        total = len(self.images)
        i = 1
        for item in self.images:
            pic = self.adlm.getPictureUrl(item['id'])
            title = self.model
            if len(self.serie) > 1:
                title = title + ' - ' + self.serie
            src = self.provider + ' - ' + self.category
            count = '%s/%s' % (i, total)
            item = {'showInfo': 'true', 'title': title, 'src': src, 'count': count, 'pic':pic}
            self.addListItem(self.CONTROL_LIST_IMG, item)
            i = i + 1
        self.getControl(self.GROUP_BROWSING).setVisible(False)
        self.getControl(self.GROUP_VIEWER).setVisible(True)
        self.setFocus(lstCtrl)
    
    def showSlideShow(self):
        self.context = self.CTX_SLIDESHOW
        self.images = self.adlm.getRandomPictures(self.slideShowIndex)
        self.imageIndex = 0
        lstCtrl = self.getControl(self.CONTROL_LIST_IMG)
        lstCtrl.reset()
        print self.images
        for item in self.images:
            item['pic'] = self.adlm.getPictureUrl(item['id'])
            item['title'] = item['model']
            if len(item['serie']) > 1:
                item['title'] = item['title'] + ' - ' + item['serie']
            item['src'] = item['provider'] + ' - ' + item['category']
            item['showInfo'] = 'true'
            self.addListItem(self.CONTROL_LIST_IMG, item)
        self.getControl(self.GROUP_BROWSING).setVisible(False)
        self.getControl(self.GROUP_VIEWER).setVisible(True)
        self.setFocus(self.getControl(self.CONTROL_LIST_LABEL_COUNT))
        
        self.setIdolInfo(lstCtrl.getListItem(self.imageIndex))
        self.resumeTimer()
    
    def toggleImageInfo(self):
        if self.showInfo == 'true':
            self.showImageInfo('false')
        else:
            self.showImageInfo('true')
    
    def showImageInfo(self, isVisible):
        if isVisible == self.showInfo:
            return
        lstCtrl = self.getControl(self.CONTROL_LIST_IMG)
        if isVisible == 'true':
            for i in range(lstCtrl.size()):
                lstCtrl.getListItem(i).setProperty('showInfo', 'true')
            self.getControl(self.GROUP_CARD).setVisible(self.showCard)
            self.showInfo = 'true'
        else:
            for i in range(lstCtrl.size()):
                lstCtrl.getListItem(i).setProperty('showInfo', 'false')
            self.getControl(self.GROUP_CARD).setVisible(False)
            self.showInfo = 'false'
            
    def setIdolInfo(self, currentControl):
        try:
            if currentControl.getProperty('idolhasinfo') == 'true':
                text = currentControl.getProperty('model') + '\n'
                text += currentControl.getProperty('idolbloodtype') + '\n'
                text += currentControl.getProperty('idolbirthday') + '\n'
                text += currentControl.getProperty('idolbirthplace') + '\n'
                text += currentControl.getProperty('idolheight') + '\n'
                text += currentControl.getProperty('idolsizes')
                if len(currentControl.getProperty('idolcup')) > 0:
                    text += ' (Cup ' + currentControl.getProperty('idolcup') + ')'
                self.getControl(self.CONTROL_CARD_TEXT).setLabel(text)
                self.getControl(self.CONTROL_CARD_INTERESTS).setLabel(getLS(34007) + currentControl.getProperty('idolinterests'))
                self.getControl(self.CONTROL_CARD_THUMB).setImage(currentControl.getProperty('idolthumb'))
                self.showCard = True
            else:
                self.showCard = False
        except:
            self.showCard = False
        if self.showInfo == 'true' and self.showCard == True:
            self.getControl(self.GROUP_CARD).setVisible(self.showCard)
        else:
            self.getControl(self.GROUP_CARD).setVisible(False)
    
    def addListItem(self, controlId, properties):
        li = xbmcgui.ListItem()
        for p in properties.keys():
            li.setProperty(p, properties[p])
        self.getControl(controlId).addItem(li)
        
    def setListItem(self, controlId, properties, index):
        lstCtrl = self.getControl(controlId).getListItem(index)
        for p in properties.keys():
            lstCtrl.setProperty(p, properties[p])
            
    def cancelTimer(self):
        try:
            self.myTimer.cancel()
        except:
            pass
            
    def resumeTimer(self):
        self.myTimer = threading.Timer(self.timerDelay, self.timerUpdate)
        self.myTimer.start()
